<template>
  <div class="warehouse-container">
    <!-- 搜索条件区域 -->
    <div style="border: 1px solid #ccc; padding: 45px;">
      <el-form :inline="true" :model="formInline" class="search-form">
        <!-- 第一行 -->
        <el-form-item label="出入库单号">
          <el-input 
            v-model="formInline.Warehouse_Code" 
            placeholder="请输入编号" 
            clearable 
            style="width: 150px; height: 32px;"
          />
        </el-form-item>
        <el-form-item label="货品">
          <el-input 
            v-model="formInline.Product_Name" 
            placeholder="请输入货品名称" 
            clearable 
            style="width: 150px; height: 32px;"
          />
        </el-form-item>
        <el-form-item label="单位">
          <el-select
            v-model="formInline.Unit_ID"
            placeholder="请选择"
            clearable
            style="width: 150px; height: 32px;"
          >
            <el-option v-for="item in unit" :label="item.unit_Name" :value="item.id" />
          </el-select>
        </el-form-item>
      
        <!-- 第二行 -->
        <el-form-item label="货品类别">
          <el-select
            v-model="formInline.Category_ID"
            placeholder="请选择"
            clearable
            style="width: 150px; height: 32px;"
          >
            <el-option v-for="item in ProductCategory" :label="item.category_Name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-select
            v-model="formInline.Warehouse_ID"
            placeholder="请选择"
            clearable
            style="width: 150px; height: 32px;"
          >
             <el-option label="仓库1" :value='1' />
            <el-option label="1号仓库" :value= '2'/>
            <el-option label="2号仓库" :value='3' />
            <el-option label="3号仓库" :value='4' />
            <el-option label="4号仓库" :value='5' />
            <el-option label="5号仓库" :value='6' />
            <el-option label="666号仓库" :value='7' />
          </el-select>
        </el-form-item>
        <el-form-item label="出库类型">
          <el-select
            v-model="formInline.Warehousing_Type"
            placeholder="请选择"
            clearable
            style="width: 150px; height: 32px;"
          >
            <el-option label="销售出库" value="销售出库" />
            <el-option label="调拨出库" value="调拨出库" />
            <el-option label="盘亏出库" value="盘亏出库" />
            <el-option label="换货出库" value="换货出库" />
            <el-option label="盘盈出库" value="盘盈出库" />
          </el-select>
        </el-form-item>
      

       
        <el-form-item label="出库日期">
          <el-date-picker
            v-model="formInline.ReviewTimeStartTime"
            type="date"
            placeholder="开始日期"
            style="width: 150px; height: 32px;"
          />
        </el-form-item>
        <el-form-item label="出库日期">
          <el-date-picker
            v-model="formInline.ReviewTimeEndTime"
            type="date"
            placeholder="结束日期"
            style="width: 150px; height: 32px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="getdata()" style="height: 32px;">查询</el-button>
          <el-button type="info" @click="resetForm" style="height: 32px; margin-left: 10px;">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-card class="stats-card outbound-card" shadow="hover">
        <div class="stats-content">
          <div class="stats-number">{{ totalOutboundCount }}</div>
          <div class="stats-label">出库数量</div>
        </div>
        <div class="stats-icon">
          <el-icon><ArrowUp /></el-icon>
        </div>
      </el-card>
      
      <el-card class="stats-card outbound-amount-card" shadow="hover">
        <div class="stats-content">
          <div class="stats-number">¥{{ totalOutboundAmount }}</div>
          <div class="stats-label">出库金额</div>
        </div>
        <div class="stats-icon">
          <el-icon><Money /></el-icon>
        </div>
      </el-card>
    </div>

    <!-- 数据表格区域 -->
    <div style="border: 1px solid #ccc; padding: 45px;">
      <!-- 表格操作按钮 -->
      <div style="margin-bottom: 15px; display: flex; justify-content: flex-end;">
        <el-button type="primary" @click="handleExport()" style="margin-right: 10px;">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <el-button type="success" @click="getdata()">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
      
      <el-table 
        :data="tableData" 
        style="width: 100%"
        class="custom-table"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="warehouse_Code" label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouse_Code" label="出库单号" width="150" />
        <el-table-column prop="reviewTime" label="出库日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.reviewTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouseType" label="业务类型" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.warehouseType == 2 ? 'danger' : 'info'"
              size="small"
            >
              {{ scope.row.warehouseType == 2 ? '出库' : '入库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warehousing_Type" label="出库类型" width="120" />
        <el-table-column prop="warehouse_Name" label="仓库名称" width="100" />
        <el-table-column prop="warehouse_InOrOutCount" label="出库数量" width="100">
          <template #default="scope">
            <span v-if="scope.row.warehouseType == 2" class="outbound-count">
              {{ scope.row.warehouse_InOrOutCount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="total_Price" label="出库金额" width="120">
          <template #default="scope">
            <span v-if="scope.row.warehouseType == 2" class="outbound-amount">
              ¥{{ scope.row.total_Price }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="reviewer" label="经办人" width="100" />
        <el-table-column prop="createUse" label="制单人" width="100">
          <template #default="scope">
            <span v-if="scope.row.createUse=='10032'">吴维昊</span>
            <span v-if="scope.row.createUse=='10036'">王雨龙</span>
            <span v-if="scope.row.createUse=='10037'">张可欣</span>
            <span v-if="scope.row.createUse=='10038'">赵姝雅</span>
            <span v-if="scope.row.createUse=='10039'">段栋兴</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="page.PageIndex"
          v-model:page-size="page.PageSize"
          :page-sizes="[15, 20, 25, 30]"
          layout="total, sizes, prev, pager, next"
          :total="page.totalCount"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import { reactive,onMounted, ref, watch, computed } from 'vue'
import { BasicsRed, FinanceRed } from '@/http/axiosHelper'
import { ElMessage, ElMessageBox } from 'element-plus'
import { BasicsWrite } from '@/http/axiosHelper'
import { useRouter } from 'vue-router'
import { statementRed } from '@/http/axiosHelper'
import { 
  Box, 
  Search, 
  Document, 
  Refresh, 
  ArrowDown, 
  ArrowUp, 
  Money, 
  List, 
  Download,
  Goods
} from '@element-plus/icons-vue'

const router=useRouter();
const dialogVisible = ref(false)

// 定义数据类型接口
interface WarehouseItem {
  warehouseType: number
  warehouse_InOrOutCount: number
  total_Price: number
  warehouse_Code: string
  reviewTime: string
  warehousing_Type: string
  warehouse_Name: string
  reviewer: string
  createUse: string
  [key: string]: any // 允许其他属性
}

function formatDate(dateStr: string) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}

// 计算出库数量和出库金额总和
const totalOutboundCount = computed(() => {
  const count = (tableData.value as WarehouseItem[])
    .filter(item => item.warehouseType == 2) // 只统计出库数据
    .reduce((sum, item) => sum + (item.warehouse_InOrOutCount || 0), 0)
  return count.toLocaleString() // 添加千分位分隔符
})

const totalOutboundAmount = computed(() => {
  const amount = (tableData.value as WarehouseItem[])
    .filter(item => item.warehouseType == 2) // 只统计出库数据
    .reduce((sum, item) => sum + (item.total_Price || 0), 0)
  return amount.toLocaleString('zh-CN', { 
    minimumFractionDigits: 2, 
    maximumFractionDigits: 2 
  }) // 添加千分位分隔符和保留两位小数
})

// 重置表单
const resetForm = () => {
  Object.assign(formInline, {
    Warehouse_Code: '',
    Warehousing_Type: '',
    Warehouse_ID: null,
    Reviewer: '',
    Product_Name: '',
    Category_ID: null,
    Unit_ID: null,
    CreateTimeStartTime: null,
    CreateTimeEndTime: null,
    ReviewTimeStartTime: null,
    ReviewTimeEndTime: null,
    CreateUse: null,
    Department_ID: null,
  })
  ElMessage.success('查询条件已重置')
}



//产品单位下拉框
const unit=ref()
const unitdata=()=>
{
    FinanceRed.get("/api/WorkOrder/GetUnitDropdown",{params:{PageIndex:page2.PageIndex,PageSize:page2.PageSize}}).then(res=>
        {
            unit.value=res.data.data
        }
    )
}
const ProductCategory=ref()
const ProductCategorydata=()=>
{
    FinanceRed.get("/api/WorkOrder/GetProductCategoryTree",{params:{PageIndex:1,PageSize:100}}).then(res=>
        {
            ProductCategory.value=res.data.data
        }
    )
}
const deplarments=ref()
const delparmentdatas=()=>
{
    FinanceRed.get("/api/WorkOrder/GetDepartmentDropdown",{params:{PageIndex:page2.PageIndex,PageSize:page2.PageSize}}).then(res=>
        {
            deplarments.value=res.data.data
        }
    )
}



const formInline = reactive({
  Warehouse_Code: '',
  Warehousing_Type: '',
  Warehouse_ID: null,
  Reviewer: '',
  Product_Name: '',
  Category_ID: null,
  Unit_ID: null,
  CreateTimeStartTime: null,
  CreateTimeEndTime: null,
  ReviewTimeStartTime: null,
  ReviewTimeEndTime: null,
  CreateUse: null,
  Department_ID: null,
})

const page=reactive({
    PageIndex:1,
    PageSize:15,
    totalCount:0
})

// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
    try {
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await FinanceRed({
            url: '/api/WorkOrder/GetWarehouse_OutExport', // 后端接口地址
            method: 'GET',
            params: {
                    PageIndex:page.PageIndex,
      PageSize:page.PageSize,
      Category_ID:formInline.Category_ID,
      CreateTimeStartTime:formInline.CreateTimeStartTime,
      CreateTimeEndTime:formInline.CreateTimeEndTime,
      CreateUse:formInline.CreateUse,
      Product_Name:formInline.Product_Name,
      ReviewTimeEndTime:formInline.ReviewTimeEndTime,
      ReviewTimeStartTime:formInline.ReviewTimeStartTime,
      Reviewer:formInline.Reviewer,
      Unit_ID:formInline.Unit_ID,
      Warehouse_Code:formInline.Warehouse_Code,
      Warehouse_ID:formInline.Warehouse_ID,
      Warehousing_Type:formInline.Warehousing_Type,
      Department_ID:formInline.Department_ID,
            }, // 对应后端 [FromQuery] 的 command 参数
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

        ElMessage.success('导出成功')

    } catch (error: any) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        ElMessage.error('导出失败，请检查参数或重新登录');
    }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '出库流水.xlsx'; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '出库流水.xlsx';
}

const page2=reactive({
    PageIndex:1,
    PageSize:100,
    totalCount:0
})

watch(page,()=>
{
  getdata();
})

onMounted(()=>
{
    getdata();
 delparmentdata();
unitdata();
delparmentdatas();
ProductCategorydata();
})



const deplarment=ref()
const delparmentdata=()=>
{
    FinanceRed.get("/api/WorkOrder/GetDepartmentDropdown",{params:{PageIndex:page2.PageIndex,PageSize:page2.PageSize}}).then(res=>
        {
            deplarment.value=res.data.data
        }
    )
}

const tableData=ref([]);

const getdata=()=>
{
    FinanceRed.get("/api/WorkOrder/GetWarehouse_OutHandle",{params:{
      PageIndex:page.PageIndex,
      PageSize:page.PageSize,
      Category_ID:formInline.Category_ID,
      CreateTimeStartTime:formInline.CreateTimeStartTime,
      CreateTimeEndTime:formInline.CreateTimeEndTime,
      CreateUse:formInline.CreateUse,
      Product_Name:formInline.Product_Name,
      ReviewTimeEndTime:formInline.ReviewTimeEndTime,
      ReviewTimeStartTime:formInline.ReviewTimeStartTime,
      Reviewer:formInline.Reviewer,
      Unit_ID:formInline.Unit_ID,
      Warehouse_Code:formInline.Warehouse_Code,
      Warehouse_ID:formInline.Warehouse_ID,
      Warehousing_Type:formInline.Warehousing_Type,
      Department_ID:formInline.Department_ID,
    }}).then(res=>
        {
tableData.value=res.data.data
page.totalCount=res.data.totalCount
        }
    )
}

const onSubmit = () => {
  console.log('submit!')
}
</script>

<style scoped>
/* 主容器 */
.warehouse-container {
  min-height: 100vh;
  background: #fff;
  padding: 20px;
}





/* 统计卡片 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30px;
  margin: 30px 0;
}

.stats-card {
  background: #fff;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stats-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
}

.stats-content {
  padding: 30px;
  position: relative;
  z-index: 2;
}

.stats-number {
  font-size: 36px;
  font-weight: 700;
  margin-bottom: 12px;
  color: #303133;
  line-height: 1.2;
}

.stats-label {
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

.stats-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 24px;
  opacity: 0.4;
  color: #303133;
}

.outbound-card {
  border-left: 4px solid #f56c6c;
}

.outbound-card .stats-number {
  color: #f56c6c;
}

.outbound-card .stats-label {
  color: #606266;
}

.outbound-amount-card {
  border-left: 4px solid #f56c6c;
}

.outbound-amount-card .stats-number {
  color: #f56c6c;
}

.outbound-amount-card .stats-label {
  color: #606266;
}



/* 表格样式 */
.custom-table {
  border-radius: 4px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header-wrapper) {
  background: #f5f7fa;
}

.custom-table :deep(.el-table__header) {
  color: #606266;
  font-weight: 600;
}

.custom-table :deep(.el-table__body) {
  color: #606266;
}

.custom-table :deep(.el-table__row) {
  color: #606266;
}

.outbound-count {
  color: #f56c6c;
  font-weight: 600;
}

.outbound-amount {
  color: #f56c6c;
  font-weight: 700;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .warehouse-container {
    padding: 16px;
  }
  
  .stats-section {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .stats-section {
    grid-template-columns: 1fr;
  }
}
</style>